<template>
  <view>
    <!-- 搜索区域 -->
    <view class="search-box">
      <uni-search-bar @input="input" @confirm="search" bgColor="#FFFFFF" :radius="100" cancelButton="auto" maxlength="10" v-model="searchValue" placeholder="搜索"></uni-search-bar>
    </view>
    <!-- 遮罩层 -->
    <view class="content-area1" v-if="searchResults.length !== 0 && isMaskShow" catchtouchmove="ture" @click="isMaskShow = false">
      <view class="sear-result" v-if='searchResults.length !== 0 && isMaskShow'>
        <view class="sear-result-item" v-for="(item,i) in searchResults" :key=i>
          <view class="item-name" @click="gotoSearchList(item)">
            <view class="item-name-left">
              <uni-icons type="search" size="17" class="icon"></uni-icons>
              <text>{{item}}</text>
            </view>
              <uni-icons type="right" size="19" class="icon"></uni-icons>
          </view>
        </view>
      </view>
    </view>
    <!-- 组件 -->
    <view class="user-polist">
      <!-- 导航区域 -->
      <view class="user-postlist-top" v-if="((searchResults.length !== 0 && !isMaskShow) || searchResults.length === 0) && !cid">
       <view class="top-item" @click="showItemByCart">
         <text>分类</text>
         <uni-icons :type="typestyle1 === false ? 'bottom' : 'top'" size="20" :color="typestyle1 === false ?'#A5A5A5' : '#4D4D48'"></uni-icons>
       </view> 
       <view class="top-item" @click="showItemBySort">
         <text>排序</text>
         <uni-icons :type="typestyle2 === false ? 'bottom' : 'top'" size="20" :color="typestyle2 === false ?'#A5A5A5' : '#4D4D48'"></uni-icons>
       </view> 
      </view>
      <!-- 内容区域 -->
      <!-- 遮罩层 -->
      <view class="content-area" v-if="((searchResults.length !== 0 && !isMaskShow) || searchResults.length === 0) && (typestyle1 === true || typestyle2 === true)" catchtouchmove="ture" @click="showCate">
      <!-- 分类区域 -->
      <view class="user-posstlist-content" v-if="typestyle1 === true">
        <!-- <view class="content-area" v-for="(item,index) in indexlistitem1" :key="index" v-if="current === 1">
          <view class="content-area-item">
            <text class="content-area-item">{{item}}</text> 
          </view>
        </view> -->
        <view class="content-area-item">
          <text class="content-area-item" @click='getListByCid(0)'>运动</text> 
        </view>
        <view class="content-area-item">
          <text class="content-area-item" @click='getListByCid(1)'>学习</text> 
        </view>
        <view class="content-area-item">
          <text class="content-area-item" @click='getListByCid(2)'>生活</text> 
        </view>
      </view>
      <view class="user-posstlist-content" v-if="typestyle2 === true">
          <view class="content-area-item">
            <text class="content-area-item" @click='getListByCid(cateId,1)'>新发布</text>
          </view>
          <view class="content-area-item">
            <text class="content-area-item" @click='getListByCid(cateId,2)'>人数多</text> 
          </view>
          <view class="content-area-item">
            <text class="content-area-item" @click='getListByCid(cateId,3)'>人数少</text> 
          </view>
       </view>
      </view>
    </view>
    <!-- 组件 -->
    <!-- 列表 -->
     <!-- v-if="cid" -->
    <view class="" v-if="messageList.length !== 0">
      <view class="" v-for="(item,i) in messageList" :key=i>
        <view class="" @click="gotoPostItem(item)">
          <user-task :postItem="item"></user-task>
        </view>
      </view>
    </view>
    <view class="nullimage" v-else>
      <image src="https://s2.loli.net/2022/05/05/r2qiah46pZPYK1O.png" mode=""></image>
      <text>空空如也</text>
    </view>
  </view>
</template>

<script>
  export default {
    watch: {
      
    },
    data() {
      return {
          //搜索
          historyList: [],
          searchResults: [],
          searchValue: '',
          searchHistory: '',
          timer: null,
          
          isBegin: 0,
          cateId: '',
          flagId: '',
          messageList: [],
          messageListBySort: [],
          total: 0,
          pagenum: 1,
          pagesize: 15,
          cid: '',
          str: '',
          //是否显示搜索提示
          isShowSearch: false,
          //防抖是否提示搜索提示
          searchFlag: true,
          total: 0,
          flag: false,
          //组件
          typestyle1: false,
          typestyle2: false,
          current: '',
          //组件
          // 遮罩层显示与隐藏
          isMaskShow: false
        };
    },
    methods: {
      //组件
      cancelSearch() {
        this.searchResults = []
      },
      showCate() {
        this.typestyle1 = false
        this.typestyle2 = false
      },
      showItemByCart() {
        this.typestyle1 = !this.typestyle1
        if(this.typestyle2 === true) this.typestyle2 = false
        this.current = 1
      },
      showItemBySort() {
        this.typestyle2 = !this.typestyle2
        if(this.typestyle1 === true) this.typestyle1 = false
        this.current = 2
      },
      //组件
      async getListByCid(catId,flagId) {
        this.typestyle1 = false
        this.typestyle2 = false
        //按发布时间，人数多少排序
        if([1,2,3].includes(flagId)) {
          this.isBegin = 1
          this.pagenum = 1
          this.flagId = flagId
          const {data:{data:{page:res}},data:info} = await uni.$http.post('/api/task/orderByDesc/' + this.pagenum + '/' + flagId + '/' + catId,this.str).catch(err => uni.$showMsg('网络错误！'))
          if(info.code !== 200) return uni.$showMsg('没有找到相应内容！')
          this.flag = false
          if(this.isBegin >= 1) {
              this.messageList = res.records
              this.isBegin += 1
            } else {
              this.messageList = [...this.messageList,...res.records]
            }
            this.total = res.total
            this.pagesize = res.size
          return
        }
        //按照分类id来查找内容
        if(catId !== this.cateId) {
          this.isBegin = 1
          this.pagenum = 1
        }
        this.flag = true
        const {data:{data:{page:res}},data:info} = await uni.$http.post('/api/task/keySearch/' + this.pagenum + '/' + catId,this.str).catch(err => uni.$showMsg('网络错误！'))
        if(res.records.length === 0) return uni.$showMsg('没有找到相应内容！')
        this.flag = false
        this.cateId = catId
        if(this.isBegin >= 1) {
            this.messageList = res.records
            this.isBegin += 1
          }
        else {
          this.messageList = [...this.messageList,...res.records]
        }
        this.total = res.total
        this.pagesize = res.size
      },
      async getList(stopR) {
        this.flag = true
        //分类页面
        if(this.cid !== undefined) {
          const {data:{data:{page:res}},data:info} = await uni.$http.get('/api/task/getTasksByCatId/' + this.cid + '/' + this.pagenum,this.str).catch(err => uni.$showMsg('网络错误！'))
          if(info.code !== 200) return uni.$showMsg('没有找到相应内容！')
          this.flag = false
          this.messageList = [...this.messageList,...res.records]
          this.total = res.total
          this.pagesize = res.size
        } else {
          // 非分类页面
          const {data:{data:{page:res}},data:info} = await uni.$http.post('/api/task/keySearch/' + this.pagenum,this.str).catch(err => uni.$showMsg('网络错误！'))
          if(info.code !== 200) return uni.$showMsg('没有找到相应内容！')
          this.flag = false
          this.messageList = [...this.messageList,...res.records]
          this.total = res.total
          this.pagesize = res.size
        }
        setTimeout(() => {
           stopR && stopR()
        },500)
        this.cateId = ''
      },
      gotoPostItem(e) {
        uni.navigateTo({
          url: '../postitem/postitem?id=' + e.serialNumber
        })
      },
      // 搜索框查询
      search(e) {
        this.searchHistory = e.value
        this.saveHistoryList()
        this.searchFlag = false
        this.searchResults = []
        this.gotoSearchList(e.value)
      },
      // 搜索框输入
      input(e) {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.searchValue = e
          if(this.searchFlag) this.getSearchList()
          this.searchFlag = true
        },250)
      },
      saveHistoryList() {
        const set = new Set(this.historyList)
        set.delete(this.searchHistory),
        set.add(this.searchHistory),
        this.historyList = Array.from(set)
        uni.setStorageSync('searchHistory', JSON.stringify(this.historyList))
      },
      async getSearchList() {
        if(this.searchValue == '') {
          //删除数据
          this.searchResults = []
          return 
        }
        const {data:{data:{message:res}},data:info} = await uni.$http.post('/api/task/fuzzyQuery',this.searchValue).catch(err => uni.$showMsg('网络错误！'))
        if(this.isShowSearch) this.searchResults = res
        // 打开遮罩
        this.isMaskShow = true
        
        this.isShowSearch = true
      },
      gotoSearchList(item) {
        //关闭搜素提示
        this.searchFlag = false
        this.searchResults = []
        //end
        this.searchHistory = item
        this.saveHistoryList()
        this.str = item
        this.messageList = []
        if(this.cid) this.getListByCid(this.cid)
        else this.getList(() => uni.hideLoading())
      }
    },
    onShow() {
      // this.messageList = []
      // this.getList()
    },
    onReachBottom() {
      if(this.pagenum * this.pagesize >= this.total) {
        uni.$showMsg('已经到底了哦~')
        return
      }
      if(this.flag) return
      uni.showLoading({
        title: '加载中...'
      })
      this.pagenum += 1
      if(this.cateId === '') this.getList(() => uni.hideLoading())
      else this.getListByCid(this.cateId,this.flagId)
    },
    onPullDownRefresh() {
      this.pagenum = 1
      this.messageList = []
      this.messageListBySort = []
      this.total = 0
      this.isBegin = 0
      this.cateId = ''
      this.flagId = ''
      this.getList(() => uni.stopPullDownRefresh())
    },
    onLoad(e) {
      this.cid = e.id
      this.str = e.str
      this.searchValue = e.str
      this.historyList = JSON.parse(uni.getStorageSync('searchHistory') || '[]')
      this.getList()
    }
  }
</script>

<style lang="scss">
   .user-polist {
     position: sticky;
     top: 56px;
     z-index: 999;
     // background-color: #F0F0F0;
     background-image: linear-gradient(to right , #FCFCF0, #FFFAE8);
     .user-postlist-top {
       width: 100%;
       display: flex;
       justify-content: space-between;
       align-items: center;
       .top-item {
         width: 50%;
         height: 100rpx;
         display: flex;
         justify-content: center;
         align-items: center;
         // border-right: 1px solid #A5A5A5;
         text {
           font-size: 15px;
           color: #8E8C8D;
         }
       }
     }
       .user-posstlist-content {
         display: flex;
         justify-content: space-around;
         align-items: center;
         width: 100%;
         background-color: #FFFAE8; 
           .content-area-item {
             margin: 20rpx 20rpx;
             text {
               font-size: 15px;
               color: #8E8C8D;   
             }
           }
         }
      }
    .content-area {
      //固定定位脱离文档流
      position: fixed;
      top: 106px;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.5);
      z-index: 999;
    }
    // 遮罩层
    .content-area1 {
      //固定定位脱离文档流
      position: fixed;
      top: 111rpx;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.5);
      z-index: 999;
    }
    .search-box {
      // background-color: #F0F0F0;
      background-image: linear-gradient(to right , #FCFCF0, #FFFAE8);
      position: sticky;
      top: 0;
      z-index: 999;
    }
    .sear-result {
        border-radius: 8px;
        // border: 1px solid #0062CC;
        .item-name {
          height: 100rpx;
          // width: 100%;
          background-color: #FFFFFF;
          border-bottom: 1px solid #FAF5DB;
          display: flex;
          justify-content: space-between;
          align-items: center;
          position: relative;
          padding: 0 20rpx;
          .item-name-left {
            display: flex;
            align-items: center;
            justify-content: center;
            text {
              margin-left: 5px;
            }
          }
      }
    }
</style>
